package com.yyx.mail;


import com.rabbitmq.client.Channel;
import com.sun.corba.se.spi.ior.IdentifiableFactory;
import com.yyx.server.pojo.Employee;
import com.yyx.server.pojo.MailConstants;
import com.yyx.server.vo.MailVo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.support.AmqpHeaders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.mail.MailProperties;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.messaging.Message;
import org.springframework.messaging.MessageHeaders;
import org.springframework.stereotype.Component;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

import javax.annotation.Resource;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.io.IOException;
import java.util.Date;

/**
 * 消息接收者
 * @author YongXin
 * @date Created in 2021/8/10 23:29
 */
@Component
public class MailReceiver {
    private static final Logger LOGGER = LoggerFactory.getLogger(MailReceiver.class);

    @Resource
    private JavaMailSender javaMailSender;
    @Resource
    private MailProperties mailProperties;
    @Resource
    private TemplateEngine templateEngine;
    @Autowired
    private RedisTemplate redisTemplate;

    @RabbitListener(queues = MailConstants.QUEUE)
    public void handler(Message message, Channel channel) throws MessagingException {
        MailVo mailVo = (MailVo) message.getPayload();
        if (mailVo.getType().equals("rz")) {
            Employee employee = mailVo.getToMailEmp();
            MessageHeaders headers = message.getHeaders();
            //消息序号
            long tag = (long) headers.get(AmqpHeaders.DELIVERY_TAG);
            String msgId = (String) headers.get("spring_returned_message_correlation");
            HashOperations hashOperations = redisTemplate.opsForHash();
            MimeMessage mimeMessage = javaMailSender.createMimeMessage();
            MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(mimeMessage);
            try {
                if (hashOperations.entries("mail_log").containsKey(msgId)) {
                    LOGGER.error("消息已经被消费=============>", msgId);
                    channel.basicAck(tag, false);
                    return;
                }
                //发件人
                mimeMessageHelper.setFrom(mailProperties.getUsername());
                //收件人
                mimeMessageHelper.setTo(employee.getEmail());
                //主题
                mimeMessageHelper.setSubject("入职欢迎邮件");
                //发送日期
                mimeMessageHelper.setSentDate(new Date());
                //邮件发送内容
                Context context = new Context();
                context.setVariable("name", employee.getName());
                context.setVariable("posName", employee.getPosition().getName());
                context.setVariable("joblevelName", employee.getJoblevel().getName());
                context.setVariable("departmentName", employee.getDepartment().getName());
                String mail = templateEngine.process("mail", context);
                mimeMessageHelper.setText(mail, true);
                //发送邮件
                javaMailSender.send(mimeMessage);
                LOGGER.info("mail发送成功！====>" + msgId);
                //将消息id存入redis中
                hashOperations.put("mail_log", msgId, "ok");
                //手动确认消息及手动ACK
                channel.basicAck(tag, false);
            } catch (Exception e) {
                try {
                    channel.basicNack(tag, false, true);
                } catch (IOException ioException) {
                    LOGGER.error("邮件发送失败======>", e.getMessage());
                }
                LOGGER.error("邮件发送失败======>", e.getMessage());
            }
        } else {//工作邮件
            String mailContent = (String) mailVo.getMailContent();
            MessageHeaders headers = message.getHeaders();
            //消息序号
            long tag = (long) headers.get(AmqpHeaders.DELIVERY_TAG);
            String msgId = (String) headers.get("spring_returned_message_correlation");
            HashOperations hashOperations = redisTemplate.opsForHash();
            MimeMessage mimeMessage = javaMailSender.createMimeMessage();
            MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(mimeMessage);
            try {
            if (hashOperations.entries("mail_log").containsKey(msgId)) {
                LOGGER.error("消息已经被消费=============>", msgId);
                channel.basicAck(tag, false);
                return;
            }
                //发件人
                mimeMessageHelper.setFrom(mailProperties.getUsername());
                //收件人
                mimeMessageHelper.setTo(mailVo.getToMail());
                //主题
                mimeMessageHelper.setSubject("工作邮件");
                //发送日期
                mimeMessageHelper.setSentDate(new Date());
                mimeMessageHelper.setText(mailContent, true);
                //发送邮件
                javaMailSender.send(mimeMessage);
                LOGGER.info("mail发送成功！====>" + msgId);
                //将消息id存入redis中
                hashOperations.put("mail_log", msgId, "ok");
                //手动确认消息及手动ACK
                channel.basicAck(tag, false);
            } catch (Exception e) {
                try {
                    channel.basicNack(tag, false, true);
                } catch (IOException ioException) {
                    LOGGER.error("邮件发送失败======>", e.getMessage());
                }
                LOGGER.error("邮件发送失败======>", e.getMessage());
            }
        }
    }
}
